//
//  LDSpritesheet.m
//  cliptest
//
//  Created by James Tong on 02/06/2010.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import "LDSpritesheet.h"

@implementation LDSpritesheet

// 讀取spritesheet description file，載入spritesheet並用NSMutableArray儲存作索引用
// fname是description file的filename
// 最後將NSMutableArray return
- (NSMutableArray *) loadWithDescriptionFile : (NSString *)fname {
	
	int cmd;
		
	// spriteArray就是整個sprite layer！
	// 用NSMutableArray就可建立一個可自動expand的array
	spritesheetArray = [[NSMutableArray alloc] init];
	
	// 取得完整的bundle path
	NSString * path = [[NSBundle mainBundle] pathForResource:  fname ofType: @"def"];
	
	fp = fopen([path cStringUsingEncoding:1],"r");
	if (fp == NULL) {
		NSLog(@"fail");		// 應該要更有更好的error handling
		return nil;
	}
	
	while (1) {
		// 讀入一行
		if (fgets(buf, 512, fp)==NULL) {
			break;
		}
		
		// 將這一行資料，交給parseDescription這個method分析
		cmd = [self parseDescription : buf];
		
		if (cmd == SSBEGIN) {				// 如果是begin command便加一個新NSMutableArray
			spritesheetArray = [[NSMutableArray alloc] init];
		}
		else if (cmd == SSFILENAME) {
			[spritesheetArray addObject:[[Texture2D alloc] initWithImagePath:_filename]];
		}
		else if (cmd == SSEND) {			// 如果是end command便設定好一切再加入spriteArray中
			break;
		}
		else if (cmd == SSUNKNOWN) {
			NSLog(@"<Unknown>");
		}
	} // while
	
	fclose(fp);
	
	return spritesheetArray;
	
} //loadWithDescriptionFile

- (int) parseDescription : (char *)s {
	char *tmp = strtok(s, ", \t\n");
	if (tmp == NULL) {
		return SSUNKNOWN;
	}
	
	if (!strcmp("beginSpritesheet",tmp)) {
		return SSBEGIN;
	}
	else if (!strcmp("endSpritesheet",tmp)) {
		return SSEND;
	}
	else if (!strcmp("filename",tmp)) {
		tmp = strtok(NULL, ", \t\n");
		_filename = [NSString stringWithUTF8String:tmp];
		return SSFILENAME;
	}

	return SSUNKNOWN;
	
} // parseDescription

@end
